package cn.net.xyan.finereport.plugin.crack;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Created by zarra on 16/12/11.
 */
public class CrackService {

    private static boolean crackSuccess = false;

//    static Logger logger = LoggerFactory.getLogger(CrackService.class);

    public static class CrackError extends RuntimeException {
        public CrackError(){
            super();
        }

        public CrackError(Throwable e){
            super(e);
        }

        public CrackError(String msg){
            super(msg);
        }

    }

    static public String errorString(Throwable e){
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        return sw.toString();
    }

    static public void traceError(Throwable e, Logger logger) {
        logger.error("\r\n" + errorString(e) + "\r\n");

    }
    public static synchronized void doCrack() {
        if (crackSuccess  == false) {
            try {
                ClassPool cp = ClassUtils.defaultClassPool();

                CtClass ctRepositoryDeal = ClassUtils.ctClass(cp, "com.fr.web.RepositoryDeal");
                CtMethod methodCheckoutObject = ClassUtils.ctMethod(ctRepositoryDeal, "checkoutObject");
                methodCheckoutObject.insertAfter("{String r = (String)$_;r=r.replace(\"{\",\"%7B\"); r = r.replace(\"}\",\"%7D\"); return r; }");
                ctRepositoryDeal.toClass();

                CtClass ctBaseUtils = ClassUtils.ctClass(cp, "com.fr.base.BaseUtils");
                CtMethod methodCheckLicExist = ClassUtils.ctMethod(ctBaseUtils, "checkLicExist");
                methodCheckLicExist.setBody("{return true;}");
                ctBaseUtils.toClass();


                cp.getAndRename("cn.net.xyan.finereport.plugin.crack.modify.LicUtils", "com.fr.stable.LicUtils").toClass();
                cp.getAndRename("cn.net.xyan.finereport.plugin.crack.modify.VersionInfoTableData", "com.fr.data.VersionInfoTableData").toClass();

                crackSuccess = true;
            } catch (Throwable e) {
        //        traceError(e, logger);
                throw new CrackError(e);
            }
        }
    }
}
